package com.dgut.softproject.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;


import javax.sql.DataSource;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandlerConfig;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandlerConfig;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandlerConfig;

    @Autowired
    private AuthenticationEntryPoint unAuthorizedEntryPointConfig;

    @Autowired
    private AccessDeniedHandler accessDeniedHandlerConfig;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**", "/img/**", "/**/*.png");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**")
                .exceptionHandling()
                .authenticationEntryPoint(unAuthorizedEntryPointConfig)
                .accessDeniedHandler(accessDeniedHandlerConfig).and()
                .cors().and()
                .csrf().disable()
                .formLogin()
                .loginProcessingUrl("/login")
                .successHandler(authenticationSuccessHandlerConfig)
                .failureHandler(authenticationFailureHandlerConfig)
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(logoutSuccessHandlerConfig)
        ;
    }

}
